//
//  XNAliyun.m
//  for_test
//
//  Created by Carlson Lee on 2017/6/7.
//  Copyright © 2017年 Carlson Lee. All rights reserved.
//

#import "XNAliyun.h"
#import <AliyunOSSiOS/OSSService.h>
#import "NSString+MD5.h"

@interface XNAliyun ()
{
    OSSClient * _client;
}
@end

NSString * const AccessKey = @"LTAIxA8ItZBUI8uk";
NSString * const SecretKey = @"cELUEaY9S7rwGBc7N0AKNbnQLnpI9H";
NSString * const endPoint = @"http://oss-cn-shanghai.aliyuncs.com";
@implementation XNAliyun

+ (instancetype)sharedInstance
{
    static XNAliyun* instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [XNAliyun new];
    });
    return instance;
}

- (void)setupEnvironment
{
    [OSSLog enableLog];
    [self initOSSClient];
}

- (void)initOSSClient
{
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey secretKey:SecretKey];
    
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    conf.maxRetryCount = 2;
    conf.timeoutIntervalForRequest = 30;
    conf.timeoutIntervalForResource = 24 * 60 * 60;
    
    _client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential clientConfiguration:conf];
}

/*
 类型：本地路径
      image
      data
 */
- (void)uploadObject:(id)object
{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName = @"test-guanjia";
    if([object isKindOfClass:[NSString class]]){
        put.uploadingData = [NSData dataWithContentsOfFile:object];
    }else if ([object isKindOfClass:[UIImage class]]){
        put.uploadingData = UIImagePNGRepresentation(object);
    }else if ([object isKindOfClass:[NSData class]]){
        put.uploadingData = object;
    }
    put.objectKey =  [NSString md5WithData:put.uploadingData];
    //optinal
//    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
//    };
//    put.contentType = @"";
//    put.contentMd5 = @"";
    
    OSSTask * putTask = [_client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if(!task.error){
            NSLog(@"sucess");
        }else{
            NSLog(@"error, %@", task.error);
        }
        return nil;
    }];
}

@end
